package io.github.wppli.trigger.http;

import cc.jq1024.middleware.token.service.ITokenService;
import com.alibaba.fastjson2.JSON;
import io.github.wppli.domain.message.model.entity.PrivateMessageEntity;
import io.github.wppli.domain.message.model.entity.UserMessageEntity;
import io.github.wppli.domain.message.service.MessageService;
import io.github.wppli.domain.websocket.service.WebsocketServerService;
import io.github.wppli.types.common.DateTimeUtils;
import io.github.wppli.types.exception.AppException;
import io.github.wppli.types.model.Response;
import io.github.wppli.types.snow.SnowflakeIdGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@CrossOrigin(value = {"${app.config.cross-origin:http://116.198.239.101:3000/}", "http://localhost:3000/"})
public class MessageController {

    private final MessageService messageService;
    private final SimpMessagingTemplate messagingTemplate;
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private final WebsocketServerService websocketServerService;
    private final ITokenService tokenService;

    /**
     * 获取receiverId用户的全部未读消息
     */
    @GetMapping("/messages/unread")
    public Response<List<UserMessageEntity>> getUnreadMessages(@RequestHeader("Authorization") String authorization) {
        try {
            String token = authorization.replace("Bearer ", "");
            String receiverId = tokenService.decode(token).getSubject();
            if (receiverId.isEmpty()) {
                log.error("Invalid request: {}", JSON.toJSONString(receiverId));
                return Response.clientError();
            }
            // 业务
            List<UserMessageEntity> privateMessageEntities = messageService.queryUnreadMessages(Long.parseLong(receiverId));

            return Response.ok(privateMessageEntities);

        }  catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<List<UserMessageEntity>>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }

    }

    /**
     * 标记信息已读
     */
    @GetMapping("/messages/markRead")
    public Response<Void> markMessageRead(@RequestHeader("Authorization") String authorization, @RequestParam("senderId") Long senderId)  {
        try {
            String token = authorization.replace("Bearer ", "");
            String receiverId = tokenService.decode(token).getSubject();
            if (receiverId.isEmpty()) {
                log.error("Invalid request, invalid token: {}", JSON.toJSONString(receiverId));
                return Response.clientError();
            }
            // 业务
            messageService.markMessageRead(Long.parseLong(receiverId), senderId);
            return Response.ok();
        } catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<Void>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }
    }


    // 发送私信（WebSocket）
    @MessageMapping("/chat/send")
    public void sendMessage(@Payload PrivateMessageEntity privateMessage, @Header("Authorization") String token)   {
//        String senderId = tokenService.decode(token).getSubject();
        String senderId = privateMessage.getSenderId().toString();
        log.info("privateMessage: {} senderId:{}", JSON.toJSONString(privateMessage), senderId);

        // 参数校验
        if (privateMessage.getContent().isEmpty() || privateMessage.getReceiverId() == null) {
            log.error("Invalid message: {}", JSON.toJSONString(privateMessage));
            return;
        }

        privateMessage.setId(snowflakeIdGenerator.nextId());
        privateMessage.setSenderId(Long.parseLong(senderId));
        privateMessage.setSendTime(DateTimeUtils.localDateTimeToString(LocalDateTime.now()));

        // 保存消息到数据库
        messageService.saveMessageAsync(privateMessage);
        // 判断用户是否在线
        if (websocketServerService.isOnline(privateMessage.getReceiverId().toString())) {
            log.info("用户在线，发送消息到队列: {}", JSON.toJSONString(privateMessage));
            messagingTemplate.convertAndSendToUser(privateMessage.getReceiverId().toString(), "/queue/messages", privateMessage);
        } else {
            log.info("用户不在线，保存消息到数据库: {}", JSON.toJSONString(privateMessage));
        }
    }

//
//    // 获取历史消息（REST API）
//    @GetMapping("/messages")
//    @ResponseBody
//    public List<PrivateMessageEntity> getMessages(
//        @RequestParam Long senderId,
//        @RequestParam Long receiverId,
//        @RequestParam(defaultValue = "0") int page
//    ) {
//        return messageService.getMessages(senderId, receiverId, PageRequest.of(page, 20));
//    }
//
//    // 标记消息已读
//    @PostMapping("/messages/mark-read")
//    public ResponseEntity<?> markAsRead(@RequestBody List<Long> messageIds) {
//        messageService.markAsRead(messageIds);
//        return ResponseEntity.ok().build();
//    }
}